package com.retallife.user.controller;

import com.retallife.user.exception.Result;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@CrossOrigin
@Api(tags = "文件传输信息类")
@RequestMapping(method = {RequestMethod.POST, RequestMethod.GET})
public class UserFileController {

    //设置文件路径
    private String uploadPath = "d:/userHead/userHeadImage";

    @RequestMapping("fileupload")
    public Result fileupload(MultipartFile file, HttpServletRequest request) throws Exception, IOException {
        //新建文件夹
        File folder = new File(uploadPath);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        // 对上传的文件重命名，避免文件重名
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));
            // 返回上传文件的访问路径
            //request.getScheme()==http
            // request.getServerName()==localhost
            //request.getServerPort() ==8081
            //filePath:  http://localhost:8081/chat/384ab238-d9da-4ff8-a1c7-8a3df623ae00.png
            String filePath = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() + "" + request.getContextPath() + "/" +"chat" +"/"+newName;
            //输出你上传后的图片映射路径地址， 这表示你上传的图片是否可以查看
            return Result.ok().put("data", filePath);
        } catch (IOException e) {
            Result.error(e.getMessage());
        }
        return Result.error();
    }
}


